/**
 * 
 */
package com.hudie;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * @author liyun
 * xml解析类，使用sax方法，用于解析google天气api返回的xml文件
 *
 */
public class SAXReader extends DefaultHandler {
	private final String FORECASE_INFORMATION="forecast_information";
    private final String CURRENT_CONDITIONS="current_conditions";
    private final String FORECAST_CONDITIONS="forecast_conditions";
    
    private List<List<String>> weatherList = null;
    private List<String> weather = null;
    
    private static String tagname = "";
    
    @Override
    public void startDocument() throws SAXException{
    	weatherList = new ArrayList<List<String>>();
    }
    
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    	if( qName.equals(FORECASE_INFORMATION)||
    			qName.equals(CURRENT_CONDITIONS)||
    			qName.equals(FORECAST_CONDITIONS)){
    		tagname = "current_conditions";
    		weather = new ArrayList<String>();
    	}else{
    		if(tagname.equals(CURRENT_CONDITIONS) && 
    				attributes.getValue("data")!=null){
    			if(!qName.contains("icon"))
    				weather.add(attributes.getValue("data"));
    		}
    	}
    		
    }
    
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {        
    	if ( qName.equals(FORECASE_INFORMATION)
                ||qName.equals(CURRENT_CONDITIONS)
                ||qName.equals(FORECAST_CONDITIONS) ) 
        {
            weatherList.add(weather);
            weather=null;
            tagname="";
        }            
    }
    
    @Override
    public void endDocument() throws SAXException {

    }

    public List<List<String>> getWeathList() {        
        if(weatherList==null||weatherList.size()<1)
        {
            return null;
        }
        else {            
            return weatherList;            
        }        
    }
    

}
